package com.lai.gulimall.ware.service.impl;

import com.lai.common.exception.BizCodeEnum;
import com.lai.common.exception.RRException;
import com.lai.common.to.OrderItemTo;
import com.lai.common.to.SkuLockStockResultTo;
import com.lai.common.to.SkuWareHasStockTo;
import com.lai.common.to.WareSkuLockTo;
import com.lai.gulimall.ware.vo.SkuHasStockVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lai.common.utils.PageUtils;
import com.lai.common.utils.Query;

import com.lai.gulimall.ware.dao.WareSkuDao;
import com.lai.gulimall.ware.entity.WareSkuEntity;
import com.lai.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<WareSkuEntity>();
        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(WareSkuEntity wareSkuEntity) {
        //判断如果还没有这个库存记录就新增
        List<WareSkuEntity> entityList = baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", wareSkuEntity.getSkuId()).eq("ware_id", wareSkuEntity.getWareId()));
        if(entityList == null || entityList.size() == 0){
            baseMapper.insert(wareSkuEntity);
        }else{
            baseMapper.updateStock(wareSkuEntity);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            //TODO 需要改进 循环查询数据库   把全部查出来使用filter过滤
            SkuHasStockVo vo = new SkuHasStockVo();
            //wms_ware_sku  根据skuId查询是否有库存
            Long count = baseMapper.getSkusHasStock(skuId);

            vo.setSkuId(skuId);
            //count > 0  hasstock: true
            vo.setHasStock(count==null?false:count > 0);
            return vo;
        }).collect(Collectors.toList());

        //select SUM(stock-stock_locked) AS STOCK from `wms_ware_sku` where sku_id = 1
        return collect;
    }


    /**
     * 为订单锁定商品库存
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean orderLockStock(WareSkuLockTo to) {

        //1、按照下单的收货地址，找到一个就近仓库，锁定库存
        //2、找到每个商品在哪个仓库都有库存
        List<OrderItemTo> locks = to.getLocks();

        List<SkuWareHasStockTo> collect = locks.stream().map((item) -> {
            SkuWareHasStockTo stock = new SkuWareHasStockTo();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪个仓库有库存
            List<Long> wareIdList = baseMapper.listWareIdHasSkuStock(skuId);
            stock.setWareIds(wareIdList);

            return stock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for (SkuWareHasStockTo hasStock : collect) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareIds();

            if (org.springframework.util.StringUtils.isEmpty(wareIds)) {
                //没有任何仓库有这个商品的库存
                throw new RRException(BizCodeEnum.INSUFFICIENT_STOCK_EXCEPTION);
            }

            //1、如果每一个商品都锁定成功,将当前商品锁定了几件的工作单记录发给MQ
            //2、锁定失败。前面保存的工作单信息都回滚了。发送出去的消息，即使要解锁库存，由于在数据库查不到指定的id，所有就不用解锁
            for (Long wareId : wareIds) {
                //锁定成功就返回1，失败就返回0
                Long count = baseMapper.lockSkuStock(skuId,wareId,hasStock.getNum());
                if (count > 0) {
                    //循环调用锁库存的方法  如果锁成功，则退出循环
                    skuStocked = true;
                    break;
                } else {
                    //当前仓库锁失败，重试下一个仓库
                }
            }
            if (!skuStocked) {
                //当前商品所有仓库都没有锁住
                throw new RRException(BizCodeEnum.INSUFFICIENT_STOCK_EXCEPTION);
            }
        }
        //3、肯定全部都是锁定成功的
        return true;
    }

}